package serial

import (
	"io"
	"sync"

	srl "github.com/tarm/serial"
)

type OnMessageCallFunc func([]byte) //消息触发
type Config = srl.Config

//tcp上网
type Serial struct {
	serialFile    io.ReadWriteCloser
	onMessageCall OnMessageCallFunc //消息触发回调
	port          string            //端口
	sync.Mutex                      //继承
	conf          *Config
}

func New(conf *Config) *Serial {
	o := new(Serial)
	o.conf = conf
	return o
}

//发送数据，如果数据很多的时候，分段发送
func (this *Serial) Write(data []byte) (int, error) {
	this.Lock()
	defer this.Unlock()
	l, e := this.serialFile.Write(data)
	return l, e
}

//关闭连接
func (this *Serial) Close() error {
	return this.serialFile.Close()
}

//当收到消息时回调
func (this *Serial) OnMessage(call OnMessageCallFunc) {
	this.onMessageCall = call
}

//
func (this *Serial) Run() error {
	var e error
	this.serialFile, e = srl.OpenPort(this.conf)
	if e != nil {
		return e
	}
	go func() {
		for {
			receive := make([]byte, 1024)
			l, e := this.serialFile.Read(receive)
			if e != nil || l <= 0 { //读取错误或无数据
				continue
			}
			data := receive[:l]
			if this.onMessageCall != nil {
				this.onMessageCall(data)
			}
		}
	}()
	return nil
}
